<?php

namespace App\Http\Controllers;



// 用户模型
use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Record;
use App\Models\Ems as EmsModel;
use App\Models\Business\Record as RecordModel;


use Illuminate\Support\Facades\Validator; // 引入Validator 门面 
use Illuminate\Http\Request; // 引入Request 门面
use Illuminate\Support\Facades\Storage; // 引入Storage 门面
use Illuminate\Support\Facades\DB; // 引入DB 门面
use Illuminate\Support\Facades\Mail; // 引入Mail 门面

class Business extends Controller
{
    // 注册
    public function register()
    {
        // request 获取请求参数  参数1：参数名  参数2：默认值
        $mobile = request('mobile', '');
        $password = request('password', '');

        // 生成密码盐
        $salt = randstr();
        // 密码加密 $password:密码  $salt:密码盐 进行拼接
        $password = md5($password . $salt);

        //组装数据
        $data = [
            'mobile' => $mobile,
            'password' => $password,
            'salt' => $salt,
            'nickname' =>  $mobile,
        ];

        // 验证规则
        $rules = [
            'mobile' => 'required|unique:business|regex: /^1[345789]\d{9}$/', //手机号
            'password' => 'required', //密码
            'salt' => 'required', //密码盐
            'nickname' => 'required', //昵称
        ];

        // 错误提示信息
        $message = [
            'mobile.required' => '手机号必填',
            'mobile.unique' => '手机号已注册',
            'mobile.regex' => '手机号格式错误',
            'password.required' => '密码必填',
            'nickname.required' => '昵称必填'
        ];

        // make 方法将会生成一个新的验证器实例
        $validator = Validator::make($data, $rules, $message);

        // 判断验证结果 fails() 方法返回 true 或 false
        // 如果验证失败，则返回一个包含错误信息的 Validator 实例
        if ($validator->fails()) {
            // first 方法检索给定字段的第一个错误信息
            return error($validator->errors()->first());
        }

        $result = BusinessModel::create($data); //添加数据

        // 判断是否注册成功
        if ($result === false) {
            return error('注册失败');
        } else {
            return success('注册成功');
        }
    }

    // 登录
    public function login()
    {
        //获取登录数据
        $mobile = request('mobile', '');
        $password = request('password', '');

        // 判断手机号是否存在 first() 获取一条数据
        $businessinfo  = BusinessModel::where('mobile', $mobile)->first();

        //判断用户是否存在
        if (!$businessinfo) {
            return error('用户不存在');
        }


        $password = md5($password . $businessinfo['salt']); //密码加密

        //判断密码是否正确
        if ($password != $businessinfo['password']) {
            return error('密码错误');
        }


        $data = [
            'id' => $businessinfo['id'],
            'mobile' => $businessinfo['mobile'],
            'nickname' => $businessinfo['nickname'],
            'avatar' => $businessinfo['avatar_text'],
            'gender' => $businessinfo['gender'],
            'province' => $businessinfo['province'],
            'city' => $businessinfo['city'],
            'district' => $businessinfo['district'],
            'createtime' => date('Y-m-d H:i:s', strtotime($businessinfo['createtime'])),
            'money' => $businessinfo['money'],
            'email' => $businessinfo['email'],
            'auth' => $businessinfo['auth'],
            'region' => $businessinfo['region_text']
        ];

        return success('登录成功', $data);
    }

    //校验
    public function check()
    {
        $mobile = request('mobile', '');
        $id = request('id', 0);

        $businessinfo = BusinessModel::where(['mobile' => $mobile, 'id' => $id])->first();

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $data = [
            'id' => $businessinfo['id'],
            'mobile' => $businessinfo['mobile'],
            'nickname' => $businessinfo['nickname'],
            'avatar' => $businessinfo['avatar_text'],
            'gender' => $businessinfo['gender'],
            'province' => $businessinfo['province'],
            'city' => $businessinfo['city'],
            'district' => $businessinfo['district'],
            'createtime' => date('Y-m-d H:i:s', strtotime($businessinfo['createtime'])),
            'money' => $businessinfo['money'],
            'email' => $businessinfo['email'],
            'auth' => $businessinfo['auth'],
            'region' => $businessinfo['region_text']
        ];

        return success('登陆成功',  $data);
    }

    // 修改个人资料
    public function profile(Request $request)
    {
        $params = request()->all();
        $id = request('id', 0);
        $password = request('password', '');

        $businessinfo = BusinessModel::find($id);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $data = [
            'nickname' => $params['nickname'],
            'gender' => $params['gender'],
            'email' => $params['email'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district']
        ];

        // 判断邮箱是否认证
        if ($businessinfo['auth'] == '1' && $params['email'] != $businessinfo['email']) {
            $data['auth'] = '0';
        }


        // 判断是否修改密码
        if (!empty($password)) {
            $data['password'] = md5($password . $businessinfo['salt']);
        }

        // 判断文件是否上传
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
            $res = uploads('avatar', $request);

            if ($res['code'] == 0) {
                return error($res['msg']);
            }
            $data['avatar'] = $res['data'];
        }

        $result = BusinessModel::where('id', $id)->update($data);

        if ($result === false) {
            //删除新文件
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                Storage::disk('uploads')->delete(basename($data['avatar']));
            }
            return error('修改失败');
        } else {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                Storage::disk('uploads')->delete(basename($businessinfo['avatar']));
            }
            return success('修改成功');
        }
    }

    // 发送邮件
    public function sendmail()
    {
        $busid = request('busid', 0);
        $email = request('email', '');

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $emailinfo = EmsModel::where('email', $email)->first();

        if ($emailinfo) {
            return error('邮件已发送，请稍后重试');
        }

        DB::beginTransaction();

        try {
            // 随机验证码
            $code = randstr(4);

            $data = [
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code,
            ];

            //校验器
            $EmsStatus = EmsModel::create($data);

            if ($EmsStatus === false) {
                return error('操作失败');
            }

            $EmailStatus = Mail::raw("邮箱验证码：$code", function ($message) use ($email) {
                $message->to($email)->subject('vue商城邮箱认证');
            });

            if ($EmailStatus === false) {
                return error('操作失败');
            }

            DB::commit();
            return success('邮件发送成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('邮件发送失败');
        }
    }

    // 邮箱认证
    public function email()
    {
        $busid = request('busid', 0);
        $email = request('email', '');
        $code = request('code', '');

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $emsinfo = EmsModel::where(['email' => $email, 'code' => $code])->first();

        if (!$emsinfo) {
            return error('邮箱认证失败，请重新认证');
        }

        DB::beginTransaction();

        try {

            $EmsStatus = EmsModel::destroy($emsinfo['id']);

            if ($EmsStatus === false) {
                return error('操作失败');
            }

            $BusinessStatus = BusinessModel::where('id', $busid)->update(['auth' => '1']);

            if ($BusinessStatus === false) {
                return error('操作失败');
            }

            DB::commit();
            return success('认证成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('认证失败');
        }
    }

    //消费记录
    public function consume()
    {
        $busid =  request('busid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $data = RecordModel::where(['busid' => $busid, 'state' => '2'])->orderBy('createtime', 'desc')->get();

        return success('', $data);
    }

    // 充值
    public function recharge()
    {
        $busid = request('busid', 0);
        $money = request('money', 0);

        if($money<=0){
            return error('充值金额必须大于0');
        }
        $businfo = BusinessModel::find($busid);
        if(!$businfo){
            return error('用户不存在');
        }
        DB::beginTransaction();
        try {
            $busresult = BusinessModel::where('id', $busid)->update(['money' => $businfo['money'] + $money]);
            if ($busresult === false) {
                return error('充值失败');
            }
            $data = [
                'busid' => $busid,
                'total' => $money,
                'content'=>'充值了'.$money.'元',
                'state' => '3',
            ];
            $recordresult = RecordModel::create($data);
            if($recordresult === false){
                return error('充值记录添加失败');
            }
            DB::commit();
            return success('充值成功');
        } catch (\Exception $e) {
            DB::rollBack();
            var_dump($e->getMessage());
            return error('充值失败');
        }
    }

    //充值记录
    public function rechargelist()
    {
        $busid = request('busid', 0);
        $businfo = BusinessModel::find($busid);
        if(!$businfo){
            return error('用户不存在');
        }
        $data = RecordModel::where(['busid'=>$busid,'state'=>'3'])->orderBy('createtime', 'desc')->get();
        return success("",$data);
    }
}
